package com.henu.art.service.Imlp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.henu.art.entity.AcademicOrigin;
import com.henu.art.entity.Research;
import com.henu.art.entity.Teacher;
import com.henu.art.mapper.TeacherMapper;
import com.henu.art.model.TeacherAcademicOriginModel;
import com.henu.art.service.ResearchService;
import com.henu.art.service.TeacherService;
import com.henu.art.util.ExcelExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExcelServiceImpl {
    private static final Map<String, String> FIELD_TO_CHINESE = new HashMap<>();
    private static final Map<String, String> ACADEMIC_ORIGIN_FIELD_TO_CHINESE = new HashMap<>();
    private static final Map<String, String> RESEARCH_FIELD_TO_CHINESE = new HashMap<>();

    static {
        FIELD_TO_CHINESE.put("id", "工号");
        FIELD_TO_CHINESE.put("name", "姓名");
        FIELD_TO_CHINESE.put("gender", "性别");
        FIELD_TO_CHINESE.put("birthDate", "出生年月");
        FIELD_TO_CHINESE.put("entryDate", "入校时间");
        FIELD_TO_CHINESE.put("employmentStatus", "任职状态");
        FIELD_TO_CHINESE.put("unitCode", "单位号");
        FIELD_TO_CHINESE.put("unitName", "单位名称");
        FIELD_TO_CHINESE.put("education", "学历");
        FIELD_TO_CHINESE.put("highestDegree", "最高学位");
        FIELD_TO_CHINESE.put("academicOrigin", "学缘");
        FIELD_TO_CHINESE.put("professionalTitle", "专业技术职称");
        FIELD_TO_CHINESE.put("subjectCategory", "学科类别");
        FIELD_TO_CHINESE.put("politicalStatus", "政治面貌");
        FIELD_TO_CHINESE.put("nationality", "国籍");
        FIELD_TO_CHINESE.put("teachingType", "任教类型");
        FIELD_TO_CHINESE.put("majorName", "任教专业名称");
        FIELD_TO_CHINESE.put("majorCode", "任教专业代码");
        FIELD_TO_CHINESE.put("teachingYears", "专业任教时间");
        FIELD_TO_CHINESE.put("isLabTech", "是否实验技术人员");
        FIELD_TO_CHINESE.put("isDoubleQualified", "是否双师双能型");
        FIELD_TO_CHINESE.put("hasEngineeringBg", "是否工程背景");
        FIELD_TO_CHINESE.put("hasIndustryBg", "是否行业背景");
        FIELD_TO_CHINESE.put("hasOverseasExp", "是否具有境外经历");
        FIELD_TO_CHINESE.put("isOutstandingIdeological", "课程思政优秀教师");
        FIELD_TO_CHINESE.put("emergencyContacts", "紧急联系人");
        FIELD_TO_CHINESE.put("emergencyPhone", "紧急联系电话");
        FIELD_TO_CHINESE.put("phone", "联系电话");
        FIELD_TO_CHINESE.put("shenfen", "身份");
    }

    static {
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("id", "工号");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("name", "姓名");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("gender", "性别");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("birthDate", "出生年月");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("entryDate", "入校时间");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("employmentStatus", "任职状态");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("unitCode", "单位号");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("unitName", "单位名称");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("professionalTitle", "专业技术职称");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("politicalStatus", "政治面貌");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("professionalLevel", "职称等级");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("zhiwu", "职务");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("dazhuan", "专科及以下");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("dazhuanMajor", "专科专业");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("benke", "本科院校");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("benkeMajor", "本科专业");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("benkeLevel", "本科级别");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("shuoshi", "硕士院校");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("shuoshiMajor", "硕士专业");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("shuoshiLevel", "硕士级别");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("phd", "博士院校");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("phdMajor", "博士专业");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("phdLevel", "博士级别");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("afterphd", "博士后院校");
        ACADEMIC_ORIGIN_FIELD_TO_CHINESE.put("afterphdLevel", "博士后级别");
    }

    static {
        RESEARCH_FIELD_TO_CHINESE.put("id", "工号");
        RESEARCH_FIELD_TO_CHINESE.put("name", "姓名");
        RESEARCH_FIELD_TO_CHINESE.put("type", "成果类型");
        RESEARCH_FIELD_TO_CHINESE.put("researchName", "成果名称");
        RESEARCH_FIELD_TO_CHINESE.put("journal", "发表期刊");
        RESEARCH_FIELD_TO_CHINESE.put("inclusion", "收录情况");
        RESEARCH_FIELD_TO_CHINESE.put("awards", "获奖情况");
        RESEARCH_FIELD_TO_CHINESE.put("date", "取得日期");
        RESEARCH_FIELD_TO_CHINESE.put("description", "成果描述");
    }

    @Resource
    private TeacherService teacherService;
    @Resource
    private AcademicOriginServiceImpl academicOriginService;
    @Resource
    private ResearchService researchService;
    @Resource
    private TeacherMapper teacherMapper;

    public boolean exportSelectedFields(HttpServletResponse response, String fields) throws Exception {
        List<String> fieldList = Arrays.asList(fields.split(","));
//        List<Teacher> teachers = teacherService.lambdaQuery()
//                .eq(Teacher::getEmploymentStatus, "在职")
//                .list();
        List<Teacher> teachers = teacherMapper.selectList((new QueryWrapper<Teacher>()).eq("employment_status", "在职"));
        List<Object[]> dataList = teachers.stream().map(teacher -> {
            Object[] row = new Object[fieldList.size()];
            for (int i = 0; i < fieldList.size(); i++) {
                String field = fieldList.get(i);
                switch (field) {
                    case "id":
                        row[i] = Optional.ofNullable(teacher.getId()).orElse("");
                        break;
                    case "name":
                        row[i] = Optional.ofNullable(teacher.getName()).orElse("");
                        break;
                    case "gender":
                        row[i] = Optional.ofNullable(teacher.getGender()).orElse("");
                        break;
                    case "birthDate":
                        row[i] = Optional.ofNullable(teacher.getBirthDate()).orElse("");
                        break;
                    case "entryDate":
                        row[i] = Optional.ofNullable(teacher.getEntryDate()).orElse("");
                        break;
                    case "unitCode":
                        row[i] = Optional.ofNullable(teacher.getUnitCode()).orElse("");
                        break;
                    case "unitName":
                        row[i] = Optional.ofNullable(teacher.getUnitName()).orElse("");
                        break;
                    case "education":
                        row[i] = Optional.ofNullable(teacher.getEducation()).orElse("");
                        break;
                    case "highestDegree":
                        row[i] = Optional.ofNullable(teacher.getHighestDegree()).orElse("");
                        break;
                    case "academicOrigin":
                        row[i] = Optional.ofNullable(teacher.getAcademicOrigin()).orElse("");
                        break;
                    case "professionalTitle":
                        row[i] = Optional.ofNullable(teacher.getProfessionalTitle()).orElse("");
                        break;
                    case "subjectCategory":
                        row[i] = Optional.ofNullable(teacher.getSubjectCategory()).orElse("");
                        break;
                    case "politicalStatus":
                        row[i] = Optional.ofNullable(teacher.getPoliticalStatus()).orElse("");
                        break;
                    case "nationality":
                        row[i] = Optional.ofNullable(teacher.getNationality()).orElse("");
                        break;
                    case "teachingType":
                        row[i] = Optional.ofNullable(teacher.getTeachingType()).orElse("");
                        break;
                    case "majorName":
                        row[i] = Optional.ofNullable(teacher.getMajorName()).orElse("");
                        break;
                    case "majorCode":
                        row[i] = Optional.ofNullable(teacher.getMajorCode()).orElse("");
                        break;
                    case "phone":
                        row[i] = Optional.ofNullable(teacher.getPhone()).orElse("");
                        break;
                    case "teachingYears":
                        row[i] = teacher.getTeachingYears() == 0 ? "无" : teacher.getTeachingYears();
                        break;
                    case "isLabTech":
                        row[i] = teacher.getIsLabTech();
                        break;
                    case "isDoubleQualified":
                        row[i] = teacher.getIsDoubleQualified();
                        break;
                    case "hasEngineeringBg":
                        row[i] = teacher.getHasEngineeringBg();
                        break;
                    case "hasIndustryBg":
                        row[i] = teacher.getHasIndustryBg();
                        break;
                    case "hasOverseasExp":
                        row[i] = teacher.getHasOverseasExp();
                        break;
                    case "isOutstandingIdeological":
                        row[i] = teacher.getIsOutstandingIdeological();
                        break;
                    case "emergencyContacts":
                        row[i] = Optional.ofNullable(teacher.getEmergencyContacts()).orElse("");
                        break;
                    case "emergencyPhone":
                        row[i] = Optional.ofNullable(teacher.getEmergencyPhone()).orElse("");
                        break;
                    case "shenfen":
                        row[i] = Optional.ofNullable(teacher.getShenfen()).orElse("");
                        break;
                    case "employmentStatus":
                        row[i] = Optional.ofNullable(teacher.getEmploymentStatus()).orElse("");
                        break;
                    default:
                        row[i] = "";
                        break;
                }
            }
            return row;
        }).collect(Collectors.toList());

        String[] colHead = fieldList.stream()
                .map(FIELD_TO_CHINESE::get)
                .toArray(String[]::new);

        (new ExcelExportUtil()).exportExcel(response, "教师基础信息", colHead, dataList);

        return true;
    }

    public boolean exportAcademicOrigin(HttpServletResponse response, String fields) throws Exception {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("employment_status", "在职");
        List<Teacher> teachers = teacherService.list(teacherQueryWrapper);
        List<AcademicOrigin> academicOrigins = academicOriginService.list(new QueryWrapper<>());

        List<TeacherAcademicOriginModel> teacherAcademicOriginModels = teachers.stream().map(teacher -> {
            TeacherAcademicOriginModel model = new TeacherAcademicOriginModel();
            model.setId(teacher.getId());
            model.setName(teacher.getName());
            model.setGender(teacher.getGender());
            model.setBirthDate(teacher.getBirthDate());
            model.setEntryDate(teacher.getEntryDate());
            model.setEmploymentStatus(teacher.getEmploymentStatus());
            model.setUnitCode(teacher.getUnitCode());
            model.setUnitName(teacher.getUnitName());
            model.setProfessionalTitle(teacher.getProfessionalTitle());
            model.setPoliticalStatus(teacher.getPoliticalStatus());
            academicOrigins.stream()
                    .filter(academicOrigin -> academicOrigin.getId() == Integer.parseInt(teacher.getId()))
                    .findFirst()
                    .ifPresent(academicOrigin -> {
                        model.setProfessionalLevel(academicOrigin.getProfessionalLevel());
                        model.setZhiwu(academicOrigin.getZhiwu());
                        model.setDazhuan(academicOrigin.getDazhuan());
                        model.setDazhuanMajor(academicOrigin.getDazhuanMajor());
                        model.setBenke(academicOrigin.getBenke());
                        model.setBenkeMajor(academicOrigin.getBenkeMajor());
                        model.setBenkeLevel(academicOrigin.getBenkeLevel());
                        model.setShuoshi(academicOrigin.getShuoshi());
                        model.setShuoshiMajor(academicOrigin.getShuoshiMajor());
                        model.setShuoshiLevel(academicOrigin.getShuoshiLevel());
                        model.setPhd(academicOrigin.getPhd());
                        model.setPhdMajor(academicOrigin.getPhdMajor());
                        model.setPhdLevel(academicOrigin.getPhdLevel());
                        model.setAfterphd(academicOrigin.getAfterphd());
                        model.setAfterphdLevel(academicOrigin.getAfterphdLevel());
                    });

            return model;
        }).collect(Collectors.toList());
        List<Object[]> dataList = teacherAcademicOriginModels.stream().map(model -> {
            return new Object[]{
                    model.getId(),
                    model.getName(),
                    model.getGender(),
                    model.getBirthDate(),
                    model.getEntryDate(),
                    model.getEmploymentStatus(),
                    model.getUnitCode(),
                    model.getUnitName(),
                    model.getProfessionalTitle(),
                    model.getPoliticalStatus(),
                    model.getProfessionalLevel(),
                    model.getZhiwu(),
                    model.getDazhuan(),
                    model.getDazhuanMajor(),
                    model.getBenke(),
                    model.getBenkeMajor(),
                    model.getBenkeLevel(),
                    model.getShuoshi(),
                    model.getShuoshiMajor(),
                    model.getShuoshiLevel(),
                    model.getPhd(),
                    model.getPhdMajor(),
                    model.getPhdLevel(),
                    model.getAfterphd(),
                    model.getAfterphdLevel()
            };
        }).collect(Collectors.toList());
        String[] colHead = {
                "工号", "姓名", "性别", "出生年月", "入校时间", "任职状态", "单位号", "单位名称",
                "专业技术职称", "政治面貌", "职称等级", "职务", "专科及以下", "专科专业", "本科院校",
                "本科专业", "本科级别", "硕士院校", "硕士专业", "硕士级别", "博士院校", "博士专业",
                "博士级别", "博士后院校", "博士后级别"
        };

        (new ExcelExportUtil()).exportExcel(response, "美术学院教职工信息统计表", colHead, dataList);

        return true;
    }

    public boolean exportResearch(HttpServletResponse response) throws Exception {
        List<Teacher> teachers = teacherService.list();
        Map<String, String> teacherNameMap = teachers.stream()
                .collect(Collectors.toMap(
                        Teacher::getId,
                        teacher -> Optional.ofNullable(teacher.getName()).orElse("未命名")
                ));

        List<Research> researches = researchService.list();
        List<Object[]> dataList = researches.stream()
                .map(research -> {
                    String teacherId = String.valueOf(Optional.ofNullable(research.getId()).orElse(0L));
                    return new Object[]{
                            teacherId,
                            Optional.ofNullable(teacherNameMap.get(teacherId)).orElse(""),
                            Optional.ofNullable(research.getType()).orElse("无"),
                            Optional.ofNullable(research.getName()).orElse("无"),
                            Optional.ofNullable(research.getJournal()).orElse("无"),
                            Optional.ofNullable(research.getInclusion()).orElse("无"),
                            Optional.ofNullable(research.getAwards()).orElse("无"),
                            Optional.ofNullable(research.getDate()).orElse("无"),
                            Optional.ofNullable(research.getDescription()).orElse("无")
                    };
                })
                .collect(Collectors.toList());

        String[] colHead = {
                "工号", "姓名", "成果类型", "成果名称", "发表期刊",
                "收录情况", "获奖情况", "取得日期", "成果描述"
        };

        (new ExcelExportUtil()).exportExcel(response, "科研成果信息", colHead, dataList);
        return true;
    }
}
